﻿﻿<?php
require_once( ROOT_SQL_CLASS . 'Sql.class.php');

class DataAccessObject extends Sql{
	/*
	 * Captura um registro baseado nos parâmetros Chave passados no atributo DataObject.
	 * @param
	 * $instanceDB Instância do banco de dados usado para efetuar a operação.
	 * $dataObject Object contendo os dados e atributos necessários para execução do processo.
	 * $properties(Opcional) Objeto de propriedades contendo os atributos necessário para a personalização da operação.
	 * @return DataObject com os dados retornados pela operação.
	 */
	function get( $instanceDB, $dataObject, $properties = '' ){
		$commandSql = "SELECT ";
		
		if ( $properties !== '' ){
			if ( $properties->getValue( "Fields" ) !== false ){
				$commandSql .= $properties->getValue( "Fields" );
			}
		} else {
			$commandSql .= $dataObject->formatAttributesForSqlQuery();
		}
		$commandSql .= " FROM " . $dataObject->table;
		
		$commandSql .= " WHERE ";
		
		$oper = "";
		foreach ( $dataObject->attributes as $key => $value ) { 
			if ( $dataObject->get($key) != "NULL" && $dataObject->attributes[$key]["key"] == "true" ){
				$commandSql .= $oper . $dataObject->attributes[$key]["name"] . " = " . $this->prepareDataToSQLQuery( $dataObject->attributes[$key]["type"], $dataObject->get($key) );
				$oper = " AND ";
			}
		} 
//		echo $commandSql;
		$this->setLog("SQL_COMMAND", "QUERY_GET", $commandSql);
		
		return $this->exec($instanceDB, "GET", $commandSql, $dataObject);
	}

	function getMax( $instanceDB, $table, $field ){
		$commandSql = "SELECT MAX(" . $field . ") AS " . $field . " FROM " . $table;
		$this->setLog("debug", "QUERY_GETMAX", $commandSql);
		$result = $this->executeQuery($instanceDB, $commandSql);
		if ( $result ){
			$row = mysql_fetch_array($result);
			$this->setLog("debug", "QUERY_GETMAX", "MAX: " . $row[$field]);
			return $row[$field];
		}
		$this->setLog("debug", "ERRO_QUERY_GETMAX", "MAX: -1");
		return -1;
	}

	function delete( $instanceDB, $dataBean ){
		$commandSql = "DELETE FROM " . $dataBean->table;
		$commandSql .= " WHERE ";
		
		$oper = "";
		foreach ( $dataBean->attributes as $key => $value ) { 
			if ( $dataBean->get($key) != "" && $dataBean->get($key) != "NULL" ){
				$commandSql .= $oper . $dataBean->attributes[$key]["name"] . " = " . $this->prepareDataToSQLQuery( $dataBean->attributes[$key]["type"], $dataBean->attributes[$key]["data"] );
				$oper = " AND ";
			}
			$dataBean->set($key, $p_object[ $this->attributes[$key]["name"] ] );
			
		} 
		//echo $commandSql;
		$this->setLog("debug", "QUERY_DELETE", $commandSql);
		return $this->exec($instanceDB, "DELETE", $commandSql);
	}

	function find( $instanceDB, $dataBean, $Properties = '' ){
		$commandSql = "SELECT ";
		$condition = " OR ";
		if ( $Properties !== '' ){
			if ( $Properties->getValue( "Fields" ) !== false ){
				$commandSql .= $Properties->getValue( "Fields" );
			} else {
				$commandSql .= $dataBean->getFields();
			}
			if ( $Properties->getValue( "Conditions" ) !== false ){
				$condition = " ".$Properties->getValue( "Conditions" )." ";
			}
		} else {
			$commandSql .= " * ";
		}
		
		$commandSql .= " FROM " . $dataBean->table;
		
		$commandSql .= " WHERE ";
		$oper = "";
		foreach ( $dataBean->attributes as $key => $value ) { 
			if ( $dataBean->attributes[$key]["data"] != "NULL" ){
				$commandSql .= $oper . $dataBean->attributes[$key]["name"] . " like " . $this->prepareDataToSQLQuery( $dataBean->attributes[$key]["type"], $dataBean->attributes[$key]["data"] );
				$oper = $condition;
			}
		}
		if ( $Properties !== '' ){
			if ( $Properties->getValue( "OrderBy" ) !== false ){
				$commandSql .= " Order By " . $Properties->getValue( "OrderBy" );
			} 
			if ( $Properties->getValue( "OrderByDesc" ) !== false ){
				$commandSql .= " Order By " . $Properties->getValue( "OrderByDesc" ) . " Desc ";
			} 
			if ( $Properties->getValue( "Limit" ) !== false ){
				$commandSql .= " Limit " . $Properties->getValue( "Limit" );
			} 
		}
		//echo $commandSql."\n\n";
		$this->setLog("debug", "QUERY_FIND", $commandSql);
		return $this->exec($instanceDB, "FIND", $commandSql, $dataBean);
	}

	function insert ( $instanceDB, $dataObject ) {
		$commandSql = "INSERT INTO " . $dataObject->table;
		$commandSql .= "(";
		$oper = "";
		foreach ( $dataObject->attributes as $key => $value ) { 
			if ( $dataObject->get($key) != "NULL" && !( $dataObject->attributes[$key]["type"] == "int" && $dataObject->get($key) == "" )){
				$commandSql .= $oper . $dataObject->attributes[$key]["name"] ;
				$oper = " , ";
			}
		} 
		$commandSql .= ") values(";
		
		$oper = "";
		foreach ( $dataObject->attributes as $key => $value ) { 
			if ( $dataObject->get($key) != "NULL" && !( $dataObject->attributes[$key]["type"] == "int" && $dataObject->get($key) == "" )){
				$commandSql .= $oper . "" . $this->prepareDataToSQLQuery( $dataObject->attributes[$key]["type"], $dataObject->get($key) );
				$oper = " , ";
			}
		} 
		$commandSql .= ")";
		//echo "\n\n".$commandSql."\n\n";
		$this->setLog("debug", "QUERY_INSERT", $commandSql);
		return $this->exec($instanceDB, "INSERT", $commandSql);
	}

	function update($instanceDB, $dataBean ) {
		$commandSql = "UPDATE " . $dataBean->table;
		$commandSql .= " SET ";
		
		$oper = "";
		foreach ( $dataBean->attributes as $key => $value ) { 
			if ( $dataBean->attributes[$key]["key"] == "false" && $dataBean->get($key) != "NULL" && !( $dataBean->attributes[$key]["type"] == "int" && $dataBean->get($key) == "" ) ){
				$commandSql .= $oper . $dataBean->attributes[$key]["name"] . " = " . $this->prepareDataToSQLQuery( $dataBean->attributes[$key]["type"], $dataBean->attributes[$key]["data"] )  . "";
				$oper = " , ";
			}
		} 

		$commandSql .= " WHERE ";
		$oper = "";
		foreach ( $dataBean->attributes as $key => $value ) { 
			if ( $dataBean->attributes[$key]["key"] == "true" ){
				$commandSql .= $oper . $dataBean->attributes[$key]["name"] . " = " . $dataBean->get($key);
				$oper = " AND ";
			}
		} 
		//echo "\n\n".$commandSql."\n\n";
		$this->setLog("debug", "QUERY_UPDATE", $commandSql);
		return $this->exec($instanceDB, "UPDATE", $commandSql);
	}

	function execute($instanceDB, $commandSql, $commandType = ''){
//		echo '\n\n'.$commandSql.'\n\n';
		$this->setLog("debug", "QUERY_CLIENT", $commandSql);
		return $this->exec($instanceDB, $commandType, $commandSql);
	}

	function exec($instanceDB, $commandType, $commandSql, $dataObject = ''){
		$result = $this->executeQuery($instanceDB, $commandSql);
		if ( $result ){
			if ( $commandType == "INSERT" ){
				return true;
			} else if ( $commandType == "UPDATE" ){
				return true;
			} else if ( $commandType == "DELETE" ){
				return true;
			} else if ( $commandType == "SELECT" ){
				$fields = mysql_num_fields($result);
				$dataResult = array();
				//echo "\n\ncont result" . count($dataResult);
				while ($row = mysql_fetch_array($result)) {
					$dataObject = new DataObject();
					for ($i=0; $i < $fields; $i++) {
						$name  = mysql_field_name($result, $i);
						$dataObject->add($name, $row[$name]);
					}
					$dataResult[] = $dataObject;
				}
				

				return $dataResult;


			} else if ( $commandType == "FIND" ){
				$data;
				while ($row = mysql_fetch_array($result)) {
					$nDataObject = $dataObject->getNewInstance();
					$data[] = $nDataObject->loadDataObjectByResultSet( $row );
				}
				return $data;

			} else if ( $commandType == "GET" ){

				$row = mysql_fetch_array($result);
				$nDataObject = $dataObject->getNewInstance();
				return $nDataObject->loadDataObjectByResultSet( $row );

			}
			return $data;
		} else {
			echo "\n\nERRO(".$commandSql.")\n\n";
			return false;
		}
	}
}

?>
